package com.haochang.chunkvod.controller.activity.cash;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import org.json.JSONArray;
import org.json.JSONObject;

import com.haochang.base.BaseActivity;
import com.haochang.base.BaseTextView;
import com.haochang.base.EventProxy;
import com.haochang.base.IEventConstant;
import com.haochang.chunkvod.R;
import com.haochang.chunkvod.app.common.intent.IntentCode;
import com.haochang.chunkvod.app.common.intent.IntentKey;
import com.haochang.chunkvod.app.database.cash.PrintInfoDao;
import com.haochang.chunkvod.app.database.order.BaseInfoDao;
import com.haochang.chunkvod.app.database.order.PartInfoDao;
import com.haochang.chunkvod.app.utils.CollectionUtils;
import com.haochang.chunkvod.app.utils.HelperUtils;
import com.haochang.chunkvod.app.utils.TimeUtils;
import com.haochang.chunkvod.app.utils.ToastUtils;
import com.haochang.chunkvod.controller.adapter.cash.CashHomePageAdapter;
import com.haochang.chunkvod.model.BaseInfo;
import com.haochang.chunkvod.model.cash.CashData;
import com.haochang.chunkvod.model.cash.PrintEnum;
import com.haochang.chunkvod.model.cash.PrintInfo;
import com.haochang.chunkvod.model.cash.VehicleInfo;
import com.haochang.chunkvod.model.custom.CustomDialogData;
import com.haochang.chunkvod.model.order.RoomInfo;
import com.haochang.chunkvod.tools.vod.event.EventObserver;
import com.haochang.chunkvod.tools.vod.thread.PrintThread;
import com.haochang.chunkvod.tools.vod.thread.ThreadPoolUtil;
import com.haochang.chunkvod.view.thirdparty.PullToRefresh.PullToRefreshBase;
import com.haochang.chunkvod.view.thirdparty.PullToRefresh.PullToRefreshGridView;
import com.haochang.chunkvod.view.vod.activity.SingleInputActivity;
import com.haochang.chunkvod.view.vod.popupWindow.VodPopWindow;
import com.haochang.chunkvod.view.vod.spinner.ContentView;
import com.haochang.chunkvod.view.vod.spinner.ExpandTabView;
import com.haochang.chunkvod.view.vod.spinner.SpinnerInfo;
import com.haochang.chunkvod.view.vod.title.TitleView;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

/**
 * @author qintao
 *         created at 2016/7/21 16:33
 *         收银首页
 */

public class CashHomePageActivity extends BaseActivity implements EventObserver
{
	private TitleView titleView;
	private BaseTextView tv_user;
	private BaseTextView tv_vehicle;
	private BaseTextView tv_date;
	private ExpandTabView expandTabView;
	private ArrayList<View> mViewArray = new ArrayList<View>();
	private PullToRefreshGridView mGridView;
	private CashHomePageAdapter adapter;
	private List<RoomInfo> roomInfoList = new ArrayList<RoomInfo>();//房间信息列表
	private List<SpinnerInfo> billStatusList = new ArrayList<SpinnerInfo>();//账单状态列表
	private List<SpinnerInfo> roomSortList = new ArrayList<SpinnerInfo>();//房间排序列表
	private List<PrintInfo> printInfoList = new ArrayList<PrintInfo>();//打印信息列表
	private List<BaseInfo> baseInfoList = new ArrayList<BaseInfo>();//颜色信息
	private boolean isVehicle = false;//是否有班次
	private CashData cashData;
	private CustomDialogData customDialogData;
	private String billStatus = "";
	private String sortType = "0";
	private String areaId = "";
	private String currentShiftEndTime;
	private Timer timer;
	private TimerTask timerTask;
	private boolean isShowTable = false;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		EventProxy.addEventListener(this, IEventConstant.CANCEL_PAY);
	}

	@Override
	public void onResume()
	{
		super.onResume();
		if (null == timer)
			timer = new Timer();
		if (null == timerTask)
			timerTask = new TimerTask()
			{
				@Override
				public void run()
				{
					handler.sendEmptyMessage(0);
				}
			};
		timer.schedule(timerTask, 0, 30000);
	}

	Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			getRoomInfoData(billStatus, sortType, areaId, false);
		}
	};

	@Override
	public void receiveParam()
	{

	}

	@Override
	public void initData()
	{
		cashData = new CashData(CashHomePageActivity.this);
		customDialogData = new CustomDialogData(CashHomePageActivity.this);
		isShowTable = HelperUtils.getHelperAppInstance().getBValue("cashShowTable", false);
		//        PrintInfoDao.getDao().clearTable(PrintInfo.class);
		printInfoList = PrintInfoDao.getDao().queryAll(PrintInfo.class);
		if (!CollectionUtils.isEmpty(printInfoList))
		{
			ThreadPoolUtil.getInstanceSingleTaskExecutor().submit(new PrintThread(PrintEnum.PRINT_DB, printInfoList));
		}
	}

	@Override
	public void initViews()
	{
		setContentView(R.layout.activity_cash_home_page);
		titleView = (TitleView) findViewById(R.id.titleView);
		titleView.setTitle("收银").setTitleOnClickListener(new TitleView.ITitleOnClickListener()
		{
			@Override
			public void onBackClick()
			{
				finish();
				animRightToLeft();
			}

			@Override
			public void onDoneClick()
			{
				List<String> list = new ArrayList<String>();
				list.add("其他收入");
				list.add("外卖");
				if (isVehicle)
				{
					list.add("换岗");
					list.add("交班");
					list.add("交班查询");
				}
				list.add("紧急列印");
				if (isShowTable)
					list.add("显示房间");
				else
					list.add("显示桌台");
				list.add("退出登录");
				int location[] = new int[2];
				ImageView img = (ImageView) titleView.findViewById(R.id.img_operates);
				img.getLocationOnScreen(location);
				int x = location[0];
				final VodPopWindow pop = new VodPopWindow(CashHomePageActivity.this, list);
				pop.showPopupWindow(titleView, x);
				pop.setPopWindowListListener(new VodPopWindow.OnPopWindowListListener()
				{
					@Override
					public void onSelectItem(int position)
					{
						if (isVehicle)
						{
							switch (position)
							{
							case 0:
								onNonOperateRevenueClick();
								break;
							case 1:
								onTakeOutClick();
								break;
							case 2:
								//换岗
								break;
							case 3:
								if (TimeUtils.compareTime(TimeUtils.getNowTime(), currentShiftEndTime, 0))
									onShiftClick();
								else
									ToastUtils.showText(CashHomePageActivity.this, "当前时间无法交班");
								break;
							case 4:
								onShiftQueryClick();
								break;
							case 5:
								onEmergencyPrintClick();
								break;
							case 6:
								if (!isShowTable)
								{
									isShowTable = true;
									HelperUtils.getHelperAppInstance().setValue("cashShowTable", true);
								} else
								{
									isShowTable = false;
									HelperUtils.getHelperAppInstance().setValue("cashShowTable", false);
								}
								break;
							case 7:
								loginOut();
								break;
							default:
								break;
							}
						} else
						{
							switch (position)
							{
							case 0:
								onNonOperateRevenueClick();
								break;
							case 1:
								onTakeOutClick();
								break;
							case 2:
								onEmergencyPrintClick();
								break;
							case 3:
								if (!isShowTable)
								{
									isShowTable = true;
									HelperUtils.getHelperAppInstance().setValue("cashShowTable", true);
								} else
								{
									isShowTable = false;
									HelperUtils.getHelperAppInstance().setValue("cashShowTable", false);
								}
								break;
							case 4:
								loginOut();
								break;
							default:
								break;
							}
						}
					}
				});
			}
		});
		tv_user = (BaseTextView) findViewById(R.id.tv_user);
		tv_vehicle = (BaseTextView) findViewById(R.id.tv_vehicle);
		tv_date = (BaseTextView) findViewById(R.id.tv_date);
		expandTabView = (ExpandTabView) findViewById(R.id.tab_view);
		ArrayList<String> mTextArray = new ArrayList<String>();
		mTextArray.add("全部状态");
		mTextArray.add("全部区域");
		mTextArray.add("排序");
		expandTabView.initView(mTextArray);
		mGridView = (PullToRefreshGridView) findViewById(R.id.grid_view);
		adapter = new CashHomePageAdapter(CashHomePageActivity.this, R.layout.item_home_page_cash_grid_layout, roomInfoList);
		mGridView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
		mGridView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>()
		{
			@Override
			public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView)
			{
				getRoomInfoData(billStatus, sortType, areaId, false);
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView)
			{

			}
		});
		mGridView.setAdapter(adapter);
		getRoomInfoData("", sortType, "", true);
	}

	/**
	 * 获取房间信息数据
	 *
	 * @param billStatus 账单状态
	 * @param sortType 排序类型
	 * @param area_id 区域id
	 * @param isLoading 是否加载转圈
	 */
	public void getRoomInfoData(String billStatus, String sortType, String area_id, boolean isLoading)
	{
		baseInfoList = BaseInfoDao.getDao().queryBuilderAll(BaseInfo.class, "is_room", !isShowTable);
		cashData.requestCashRoomStatus(billStatus, sortType, area_id, isShowTable, isLoading, new CashData.IRoomStatusListener()
		{
			@Override
			public void onRequestSuccess(List<RoomInfo> list, List<SpinnerInfo> statusList, List<SpinnerInfo> sortList, VehicleInfo info, boolean clear)
			{
				if (!CollectionUtils.isEmpty(list))
				{
					if (clear)
						roomInfoList.clear();
					roomInfoList.addAll(list);
				} else
				{
					roomInfoList.clear();
					ToastUtils.showText(context, "此分区暂时没有房间");
				}
				adapter.setBaseInfoList(baseInfoList);
				adapter.replaceAll(roomInfoList);
				if (!CollectionUtils.isEmpty(statusList))
				{
					billStatusList.clear();
					billStatusList.addAll(statusList);
				}
				if (!CollectionUtils.isEmpty(sortList))
				{
					roomSortList.clear();
					roomSortList.addAll(sortList);
				}
				setSpinnerContent();
				if (info != null)
				{
					if (!TextUtils.isEmpty(info.getShiftName()))
					{
						isVehicle = true;
						adapter.setVehicle(true);
					}
					if (!TextUtils.isEmpty(info.getCurrent_shift_end_time()))
					{
						currentShiftEndTime = TimeUtils.getDayString(info.getBusiness_date()) + " " + info.getCurrent_shift_end_time();
					}
					HelperUtils.getHelperInstance().setValue(IntentKey.USERNAME, info.getStaff_name());
					tv_user.setText(String.format("操作员:%s", info.getStaff_name()));
					tv_vehicle.setText(String.format("班次:%s", info.getShiftName()));
					tv_date.setText(
							String.format("%s", (TimeUtils.getDayString(info.getBusiness_date()) + " " + TimeUtils.getWeekOfDate(info.getBusiness_date()))));
				}
			}

			@Override
			public void onFinish()
			{
				if (mGridView.getVisibility() == View.VISIBLE && mGridView.isRefreshing())
					mGridView.onRefreshComplete();
			}
		});
	}

	/**
	 * 点击外卖
	 */
	private void onTakeOutClick()
	{
		Intent intent = new Intent(CashHomePageActivity.this, TakeOutActivity.class);
		startActivity(intent);
	}

	/**
	 * 点击营业外收入
	 */
	private void onNonOperateRevenueClick()
	{
		Intent intent = new Intent(CashHomePageActivity.this, NonOperatingRevenueActivity.class);
		startActivity(intent);
	}

	/**
	 * 点击交班
	 */
	private void onShiftClick()
	{
		Intent intent = new Intent(CashHomePageActivity.this, SingleInputActivity.class);
		intent.putExtra(IntentKey.CUSTOM_DIALOG_CONTENT_HINT, "请输入密码");
		intent.putExtra(IntentKey.CUSTOM_DIALOG_TITLE, "交班");
		intent.putExtra(IntentKey.BTN_SURE, "确定");
		intent.putExtra(IntentKey.BTN_CANCEL, "取消");
		intent.putExtra(IntentKey.ACTIVITY_ENUM, SingleInputActivity.ActivityEnum.PERMISSION);
		startActivityForResult(intent, IntentCode.SHIFT_REQUEST);
	}

	/**
	 * 点击紧急列印
	 */
	private void onEmergencyPrintClick()
	{
		Intent intent = new Intent(CashHomePageActivity.this, SingleInputActivity.class);
		intent.putExtra(IntentKey.CUSTOM_DIALOG_CONTENT_HINT, "请输入密码");
		intent.putExtra(IntentKey.CUSTOM_DIALOG_TITLE, "紧急列印");
		intent.putExtra(IntentKey.BTN_SURE, "确定");
		intent.putExtra(IntentKey.BTN_CANCEL, "取消");
		intent.putExtra(IntentKey.ACTIVITY_ENUM, SingleInputActivity.ActivityEnum.PERMISSION);
		startActivityForResult(intent, IntentCode.EMERGENCY_PRINT_REQUEST);
	}

	/**
	 * 点击交班查询
	 */
	private void onShiftQueryClick()
	{
		Intent intent = new Intent(CashHomePageActivity.this, ShiftQueryActivity.class);
		startActivity(intent);
	}

	/**
	 * 设置选择栏数据内容
	 */
	private void setSpinnerContent()
	{
		int totalNum = 0;
		boolean isStatusSelected = false;
		for (int i = 0; i < billStatusList.size(); i++)
		{
			SpinnerInfo itemInfo = billStatusList.get(i);
			if (!TextUtils.isEmpty(billStatus) && billStatus.equals(itemInfo.getCode()))
			{
				isStatusSelected = true;
				itemInfo.setSelected(true);
			}
			totalNum += itemInfo.getCount();
		}
		billStatusList.add(0, new SpinnerInfo("", "全部状态(" + totalNum + ")", !isStatusSelected));

		boolean isAreaSelected = false;
		List<SpinnerInfo> listMiddle = PartInfoDao.getDao().queryPartInfo();
		for (int i = 0; i < listMiddle.size(); i++)
		{
			SpinnerInfo itemInfo = listMiddle.get(i);
			if (!TextUtils.isEmpty(areaId) && areaId.equals(itemInfo.getCode()))
			{
				isAreaSelected = true;
				itemInfo.setSelected(true);
			}
		}
		listMiddle.add(0, new SpinnerInfo("", "全部区域", !isAreaSelected));

		for (int i = 0; i < roomSortList.size(); i++)
		{
			SpinnerInfo itemInfo = roomSortList.get(i);
			if (!TextUtils.isEmpty(sortType) && sortType.equals(itemInfo.getCode()))
			{
				itemInfo.setSelected(true);
			}
		}
		final ContentView viewLeft = new ContentView(CashHomePageActivity.this, billStatusList);
		final ContentView viewMiddle = new ContentView(CashHomePageActivity.this, listMiddle);
		final ContentView viewRight = new ContentView(CashHomePageActivity.this, roomSortList);
		mViewArray.clear();
		mViewArray.add(viewLeft);
		mViewArray.add(viewMiddle);
		mViewArray.add(viewRight);
		expandTabView.setValue(mViewArray);
		viewLeft.setOnSelectListener(new ContentView.OnSelectListener()
		{

			@Override
			public void getValue(String code, String showText)
			{
				billStatus = code;
				onRefresh(viewLeft, showText);
			}
		});

		viewMiddle.setOnSelectListener(new ContentView.OnSelectListener()
		{

			@Override
			public void getValue(String code, String showText)
			{
				areaId = code;
				onRefresh(viewMiddle, showText);
			}
		});

		viewRight.setOnSelectListener(new ContentView.OnSelectListener()
		{

			@Override
			public void getValue(String code, String showText)
			{
				sortType = code;
				onRefresh(viewRight, showText);
			}
		});
	}

	/**
	 * 刷新ui
	 *
	 * @param view 需要刷新的view
	 * @param showText  显示信息
	 */
	private void onRefresh(View view, String showText)
	{
		expandTabView.onPressBack();
		int position = getPosition(view);
		String title = "";
		if (showText.contains("("))
			title = showText.substring(0, showText.indexOf("("));
		else
			title = showText;
		if (position >= 0 && !expandTabView.getTitle(position).equals(title))
		{
			expandTabView.setTitle(title, position);
		}
		Toast.makeText(CashHomePageActivity.this, showText, Toast.LENGTH_SHORT).show();
		getRoomInfoData(billStatus, sortType, areaId, true);
	}

	/**
	 * 得到当前view的下标
	 *
	 * @param tView
	 * @return
	 */
	private int getPosition(View tView)
	{
		for (int i = 0; i < mViewArray.size(); i++)
		{
			if (mViewArray.get(i) == tView)
			{
				return i;
			}
		}
		return -1;
	}

	@Override
	public void onBackPressed()
	{
		if (!expandTabView.onPressBack())
		{
			finish();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == IntentCode.SHIFT_REQUEST && resultCode == RESULT_OK && data != null)
		{
			//交班操作
			customDialogData.requestShift(new CustomDialogData.IShiftListener()
			{
				@Override
				public void onRequestSuccess(JSONObject jsonObject)
				{
					PrintInfo printInfo = new PrintInfo();
					printInfo.setType(PrintEnum.PRINT_SHIFT.getName());
					printInfo.setContent(jsonObject.optJSONObject("shift").toString());
					ThreadPoolUtil.getInstanceSingleTaskExecutor().submit(new PrintThread(PrintEnum.PRINT_SHIFT, printInfo));
					PrintInfo printInfo2 = new PrintInfo();
					printInfo2.setType(PrintEnum.CASH_MONEY.getName());
					printInfo2.setContent(jsonObject.optJSONObject("gotmoney").toString());
					ThreadPoolUtil.getInstanceSingleTaskExecutor().submit(new PrintThread(PrintEnum.CASH_MONEY, printInfo2));
					loginOutDone();
				}
			});
		} else if (requestCode == IntentCode.EMERGENCY_PRINT_REQUEST && resultCode == RESULT_OK && data != null)
		{
			//紧急列印操作
			cashData.requestUrgencyInfo(new CashData.IPrintInfoListener()
			{

				@Override
				public void onRequestSuccess(final JSONObject jsonObject)
				{
					if (jsonObject != null)
					{
						JSONArray jsonArray = jsonObject.optJSONArray("list");
						if (jsonArray != null && jsonArray.length() > 0)
						{
							List<PrintInfo> printInfoList = new ArrayList<PrintInfo>();
							for (int i = 0; i < jsonArray.length(); i++)
							{
								PrintInfo info = new PrintInfo();
								info.setId(UUID.randomUUID().toString());
								info.setType(PrintEnum.PRINT_URGENCY.getName());
								info.setContent(jsonArray.optJSONObject(i).toString());
								printInfoList.add(info);
							}
							try
							{
								PrintInfoDao.getDao().insertAll(PrintInfo.class, printInfoList);
							} catch (Exception e)
							{
								e.printStackTrace();
							}
							ThreadPoolUtil.getInstanceSingleTaskExecutor().submit(new PrintThread(PrintEnum.PRINT_URGENCY));
						}
					}
				}

				@Override
				public void onRequestFail(int errno, String errMsg)
				{
					ToastUtils.showText(CashHomePageActivity.this, "获取紧急列印信息失败");
				}

			});

		} else if (requestCode == IntentCode.CHECKOUT_REQUEST && resultCode == RESULT_OK)
		{
			//结账成功后返回.重新请求首页数据
			getRoomInfoData(billStatus, sortType, areaId, false);
		}
	}

	@Override
	public void onNotify(Object sender, int eventId, Object... args)
	{
		switch (eventId)
		{
		case IEventConstant.CANCEL_PAY:
			getRoomInfoData(billStatus, sortType, areaId, false);
			break;
		default:
			break;
		}
	}

	@Override
	protected void onDestroy()
	{
		EventProxy.removeEventListener(IEventConstant.CANCEL_PAY, this);
		cancelTask();
		super.onDestroy();
	}

	private void cancelTask()
	{
		if (timer != null)
		{
			timer.cancel();
			timer = null;
		}
		if (timerTask != null)
		{
			timerTask.cancel();
			timerTask = null;
		}
	}

	@Override
	public void onPause()
	{
		super.onPause();
		cancelTask();
	}

}
